<?php
  class LoginHandler
  {
    private $m_database = NULL;  
    public function __construct($database)
    {
      $this->m_database = $database;
    }
     
    // Islogged in used for checking, No inparameters
    public static function IsLoggedIn()
    {
      // Checking if the user is logged in
      if(isset($_SESSION['details']) == true)
      {
        return true;
      }
      else
      {
        return false;
      }
    }
    
    // Setting last visit cookie
    public function SetLastVisitCookie()
    {
        if(isset($_COOKIE['LastVisit']))
    	{
    		$_SESSION['currentLastVisit'] = $_COOKIE['LastVisit']; 		
    	}
    	
    	$month = 2592000 + time();
    	setcookie("LastVisit", date("F jS - g:i a"), $month);
    }
    
    // Retrive last visit cookie
    public function RetriveLastVisitCookie()
    {
    	$latest = "";
    	if(isset($_SESSION['currentLastVisit']))
    	{
    		$latest = $_SESSION['currentLastVisit']; 		
    	}
    	return $latest;
    }
    
    // Returns a session array with the user object 
    public function getUser()
    {
    	return $_SESSION['details']; 
    }
    
    public function CheckIfVerified($username)
    {
      if($stmt = $this->m_database->getPrepareStatement("SELECT rank FROM users WHERE username=?"))
      {
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $stmt->bind_result($status);
        $stmt->fetch();
        $stmt->close();
        
        if($status > 0)
        {
          return true;
        }
        else
        {
          return false;
        }
      }
    }
    
    // Dologin to login, takes two parameters (name, pass)
    public function DoLogin($username, $password)
    {
      // Escape to prevent sql injection easy attack  
      $username = $this->m_database->realEscapeString($username);
      $password = $this->m_database->realEscapeString($password);
      // Attempt statement
      if($stmt = $this->m_database->getPrepareStatement("SELECT * FROM users WHERE username=?"))
      {        
        // Binds parameters, executes, binds result, fetch and close 
        $stmt->bind_param("s",$username);
        $stmt->execute();
        $stmt->bind_result($pk, $rank, $born, $reg, $country, $firstname, $lastname, $infoUser, $infoPass, $infoEmail, $activationKey);
        $stmt->fetch();
        $stmt->close();
        
        // MD5 check
        if(md5($password) == $infoPass)
        {
          
          // Checking verified user                    
          if($this->CheckIfVerified($infoUser) == false)
          {
            return false;
          }  
          
          // If pk was given a value, and is INT, give session the user object
          if($pk !== null && filter_var($pk, FILTER_VALIDATE_INT) == true)
          {
          	$_SESSION['details'] = new User($pk, $rank, $born, $reg, $country, $firstname, $lastname, $infoUser, $infoPass, $infoEmail, $activationKey);              
            return true;
          }
        }      
      }
      $username = null;
      $password = null;
      $infoPass = null;
      $infoUser = null;
      $pk = null;
      
      return false;
    }
    
    // Dologout used to logout & unset
    // No inparameteres, or return values
    public function DoLogout()
    {
      if(isset($_SESSION['details']))
      {
        unset($_SESSION['details']);
        
        setcookie("user", "", time() - 3600);
        setcookie("pass", "", time() - 3600);
        
        unset($_COOKIE['user']);
        unset($_COOKIE['pass']);
        
        // Setcookie backwards in time for total removal     
      }
    }
        
    // Automated test , LoginHandler
    public function Test()
    {  
      $this->DoLogout();  
            
      // Checking if youre logged in
      if($this->IsLoggedIn())
      {
        echo "Error, you are logged in";
        return false;
      }
      
      // Trying to login with faulty details
      if($this->DoLogin('nouser', 'nopass'))
      {
        echo "Error you were logged in with faulty details(dologin)";
        return false;
      }
      
      // Trying to login with null
      if($this->DoLogin('', ''))
      {
        echo "Error you were logged in with null";
        return false;
      }
      
      // Loggin in with correct details
      if(!$this->DoLogin('Adamzone89', 'gZ9AB!Cabc'))
      {
        echo "Error, you where not logged in, when you should be (dologin2)";
        return false;
      }

      // Checking if you are logged in
      if(!$this->IsLoggedIn())
      {
        echo "Error, you are not logged in";  
        return false;
      }
      
      // Logging out & checking it
      $this->DoLogout();
      if($this->IsLoggedIn())
      {
        echo "Error, logout failed";
        return false;
      }

      // Attempting a combo
      if($this->DoLogin('goodUser', 'badPassword'))
      {
        echo "Error, you shouldnt be able to login with this combo";
        return false;
      }
      
      return true;
    }
    
  }
